import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer

# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']  
plt.rcParams['axes.unicode_minus'] = False  

# 读取数据
data_path = 'D:\\学习&科研\\华为手表项目\\华为数据\\试验记录表\\all_stages_df_statistics.csv'
df = pd.read_csv(data_path)    

# 选择特征
features = df[['speed', 'polar_hr_mean', 'polar_hr_min', 'polar_hr_max', 
                'polar_hr_median', 'polar_hr_q1', 'polar_hr_q3', 
                'polar_rr_mean', 'polar_rr_median', 'polar_rr_q1', 
                'polar_rr_q3', 'sex', 'age', 'hight', 'weight']]

# 处理缺失值
imputer = SimpleImputer(strategy='mean')  # 使用均值填充
features = imputer.fit_transform(features)

# 标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(features)

# KMeans聚类
kmeans = KMeans(n_clusters=3, random_state=42)
clusters = kmeans.fit_predict(X_scaled)

# 将聚类结果添加到数据框
df['Cluster'] = clusters

# 绘制聚类结果
plt.figure(figsize=(10, 6))
plt.scatter(df['speed'], df['polar_hr_mean'], c=df['Cluster'], cmap='viridis', alpha=0.5)
plt.title('聚类结果示意图')
plt.xlabel('速度')
plt.ylabel('平均心率')
plt.colorbar(label='聚类标签')
plt.grid()
plt.savefig('聚类结果示意图.png')  # 保存图片
plt.show()

# 3D聚类
features_3d = df[['speed', 'polar_hr_mean', 'age']]
features_3d = imputer.fit_transform(features_3d)  # 处理缺失值
X_scaled_3d = scaler.fit_transform(features_3d)

# KMeans聚类
kmeans_3d = KMeans(n_clusters=3, random_state=42)
clusters_3d = kmeans_3d.fit_predict(X_scaled_3d)

# 将聚类结果添加到数据框
df['Cluster_3D'] = clusters_3d

# 绘制3D聚类结果
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111, projection='3d')
scatter = ax.scatter(df['speed'], df['polar_hr_mean'], df['age'], c=df['Cluster_3D'], cmap='viridis', alpha=0.5)
ax.set_title('3D 聚类结果示意图')
ax.set_xlabel('速度')
ax.set_ylabel('平均心率')
ax.set_zlabel('年龄')
plt.colorbar(scatter, label='聚类标签')
plt.savefig('3D_聚类结果示意图.png')  # 保存图片 
plt.show()
